package com.github.slprj.slake.common;

/**
 * 生命周期抽象, 定义了启动服务,结束服务的流程,进行状态的改变
 * - 定义了生命周期的状态标识
 * - 具体的启动细节交给子类来实现
 *
 * @author YangXiaoLong
 * 2022/8/23 10:49
 */
public class AbstractLifeCircle implements LifeCircle {

    protected enum LifeStatus {
        /**
         * 未启动
         */
        not_start,
        /**
         * 启动中
         */
        starting,
        /**
         * 启动完成, 运行中
         */
        running,
        /**
         * 停止中
         */
        stopping,
        /**
         * 停止完成
         */
        stopped;
    }

    protected volatile LifeStatus status = LifeStatus.not_start;

    @Override
    public final synchronized void start() throws Exception {
        if (status == LifeStatus.not_start) {
            //正在启动
            status = LifeStatus.starting;
            doStart();
            //启动成功
            status = LifeStatus.running;
        } else {
            throw new IllegalAccessException("error status" + status);
        }
    }

    protected void doStart() throws Exception {
    }

    @Override
    public final synchronized void stop() throws Exception {
        if (status == LifeStatus.running) {
            status = LifeStatus.stopping;
            doStop();
            status = LifeStatus.stopped;
        }
    }

    protected void doStop() throws Exception {
    }
}
